<?php

namespace App\Http\Controllers\Auth;

use Validator;
use App\Model\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use \App\Rules\StrongPassword as StrongPassword;
use \App\Model\JSONResponse as CodeBaseResponse;

class RegisterController extends Controller
{

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('guest');
    }

    /**
     * 验证函数
     *
     * @param array $data 待验证数据
     *
     * @return Validator
     *
     * @var \Illuminate\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|min:3|max:25|unique:users',
            'nick_name' => 'bail|required|min:3|max:15',
            'phone' => [
                'bail',
                'required',
                'string',
                'regex:/\d/',
                'size:11',
                'unique:users',
            ],
            'email' => 'required|email|unique:users',
            'password' => [
                'required',
                'min:6',
                'max:512',
                new StrongPassword,
            ],
        ]);
    }

    /**
     * 新建用户
     *
     * @param data 用户数据
     * @return json
     */
    public function index(Request $request)
    {
        $data = $request->all();
        $validator = $this->validator($data);
        if ($validator->fails()) {
            return response()->json(CodeBaseResponse::error($validator->errors()));
        }
        // 用户信息进库预处理
        foreach ($data as $key => $value) {
            if ($key === 'password') {
                $data[$key] = Hash::make($value);
            }
        }
        $users = User::create($data);
        return response()->json(CodeBaseResponse::success('用户创建成功', [
            'userid' => $users->id,
        ]));
    }
}
